package indi.zhifa.study2025.test.rabbitmq.ps.producer;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import indi.zhifa.engine.core.common.utils.TimeUtil;
import indi.zhifa.study2025.test.rabbitmq.common.Constant;
import indi.zhifa.study2025.test.rabbitmq.common.entity.OrderMsg;
import indi.zhifa.study2025.test.rabbitmq.common.utils.NWRabbitUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

public class PSProcedureApplication {

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = null;
        Connection connection = null;
        try{
            connection = NWRabbitUtils.getConnection();
            channel = connection.createChannel();
            // 声明交换机
            channel.exchangeDeclare(Constant.PS_EXCHANGE_NAME, BuiltinExchangeType.FANOUT,true);
            // 如果队列不存在，则创建队列
            channel.queueDeclare(Constant.PQ_QUE_NAME1, true, false, false, null);
            channel.queueDeclare(Constant.PQ_QUE_NAME2, true, false, false, null);

            // 绑定队列与交换机
            channel.queueBind(Constant.PQ_QUE_NAME1,Constant.PS_EXCHANGE_NAME,"");
            channel.queueBind(Constant.PQ_QUE_NAME2,Constant.PS_EXCHANGE_NAME,"");

            for (int i = 0; i < 100; i++) {
                String code = RandomUtil.randomString(8);
                OrderMsg orderMsg = new OrderMsg();
                orderMsg.setCode(code);
                orderMsg.setBillTime(LocalDateTime.now());
                orderMsg.setBillTimeSecond(TimeUtil.nowSecond());
                orderMsg.setAmount(RandomUtil.randomBigDecimal(BigDecimal.valueOf(10), BigDecimal.valueOf(1000)));

                String jsonMsg = JSON.toJSONString(orderMsg);
                channel.basicPublish(Constant.PS_EXCHANGE_NAME, "", null, jsonMsg.getBytes());
                System.out.println("push msg "+orderMsg);
                Thread.sleep(200);
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {
            channel.close();
            connection.close();
        }
    }

}
